package com.ninja.seata.service;

import com.ninja.seata.client.AccountClient;
import com.ninja.seata.client.StorageClient;
import com.ninja.seata.domain.Order;
import com.ninja.seata.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author Ninja
 * @Date 2020/6/19
 **/

@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;

    //下面是我们发生分布式事务问题的函数
    @GlobalTransactional(rollbackFor = Exception.class)
    public Long createOrder(Order order){
        log.info("----->饿了么来订单啦");
        //1: 首先模拟业务线创建一个订单数据
        orderMapper.addOrder(order);
        //2: 然后我们调用库存服务，减库存
        storageClient.reduce(order.getProductId(),order.getCount());
        //3: 调用账户服务，扣取该用户的钱钱
        accountClient.reduce(order.getUserId(),order.getMoney());
        //最后这个订单算完完成，我们修改订单状态为已完成：1
        orderMapper.updateStatus(order.getId());
        log.info("----->恭喜xx选手成功接单,订单号为:" + order.getId());
        return order.getId();
    }
}
